import Validation from 'backbone-validation';
import Mn from 'backbone.marionette';
import FormBehavior from 'base/behaviors/FormBehavior.js';
import DateWidget from 'widgets/DateWidget.js';
import InputWidget from 'widgets/InputWidget.js';
import CheckboxListWidget from 'widgets/CheckboxListWidget.js';
import PercentInputWidget from 'widgets/PercentInputWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import Radio from 'backbone.radio';


const SupplierInvoiceFormView = Mn.View.extend({
    tagName: 'div',
    behaviors: [FormBehavior],
    template: require('./templates/SupplierInvoiceFormView.mustache'),
    regions: {
        date: '.date',
        remote_invoice_number: '.remote_invoice_number',
        supplier_orders: '.supplier-orders',
        supplier_id: '.supplier_id',
        payer_id: '.payer_id',
        advance_percent: '.advance_percent',
    },
    childViewEvents: {
        'finish': 'onFinish',
        'change': 'onChange',
    },
    initialize() {
        this.config = Radio.channel('config');
        this.orders_options = this.config.request(
            'get:options',
            'supplier_orders'
        );
        this.suppliers_options = this.config.request(
            'get:options',
            'suppliers'
        );
        this.payers_options = this.config.request(
            'get:options',
            'payers'
        );

        this.facade = Radio.channel('facade');
        this.listenTo(this.facade, 'bind:validation', this.bindValidation);
        this.listenTo(this.facade, 'unbind:validation', this.unbindValidation);
    },
    bindValidation() {
        Validation.bind(this);
    },
    unbindValidation() {
        Validation.unbind(this);
    },
    onChange(name, value) {
        this.model.set(name, value);
        this.triggerMethod('invoice:modified', name, value);
        this.triggerMethod('data:modified', name, value);
    },
    onFinish(name, value) {
        this.model.set(name, value);
        this.triggerMethod('invoice:modified', name, value);
        this.triggerMethod('data:persist', name, value);
    },
    showDatePicker() {
        const editable = this.config.request('get:form_section', 'general:date')['edit'];
        const view = new DateWidget({
            value: this.model.get('date'),
            title: 'Date',
            description: 'Date de la facture',
            field_name: 'date',
            editable: editable,
            required: true,
        });
        this.showChildView('date', view);
    },
    showRemoteInvoiceNumber() {
        let editable = this.config.request('get:form_section', 'general:remote_invoice_number')['edit'];
        const view = new InputWidget({
            value: this.model.get('remote_invoice_number'),
            title: 'N° de facture du fournisseur',
            field_name: 'remote_invoice_number',
            editable: editable,
            required: true,
        });
        this.showChildView('remote_invoice_number', view);
    },
    showSupplierId() {
        const editable = this.config.request('get:form_section', 'general:supplier_id')['edit'];
        const widget_params = {
            options: this.suppliers_options,
            title: 'Fournisseur',
            field_name: 'supplier_id',
            editable: editable,
            value: this.model.get('supplier_id'),
            required: true,
        }
        if (!this.model.has('supplier_id')) {
            widget_params['placeholder'] = 'Sélectionner';
        }

        const view = new SelectWidget(widget_params);
        this.showChildView('supplier_id', view);
    },
    showSupplierOrders() {
        const editable = this.config.request('get:form_section', 'general:supplier_orders')['edit'];
        const supplier_id = this.model.get('supplier_id');
        const view = new CheckboxListWidget({
            value: this.model.get('supplier_orders'),
            title: 'Commandes fournisseur associées',
            field_name: 'supplier_orders',
            editable: editable,
            options: this.orders_options,
            togglable: true,
            multiple: true,
            id_key: 'id',
            optionFilter: function (option, currentOption) {
                // Keep only the orders from same supplier
                return (
                    (currentOption == undefined && supplier_id && option.supplier_id == supplier_id) ||
                    (currentOption && option.supplier_id == currentOption.supplier_id)
                );
            },
            removeItemConfirmationMsg: "Si vous rompez le lien vers cette " +
                "commande, toutes les lignes associées seront retirées de la" +
                " présente facture fournisseur.",
        });
        this.showChildView('supplier_orders', view);
    },
    showPayerId() {
        const editable = this.config.request('get:form_section', 'general:payer_id')['edit'];
        const view = new SelectWidget({
            options: this.payers_options,
            title: 'Entrepreneur',
            editable: editable,
            field_name: 'payer_id',
            placeholder: 'Sélectionner',
            value: this.model.get('payer_id'),
        });
        this.showChildView('payer_id', view)
    },
    showCaePercentage() {
        const editable = this.config.request('get:form_section', 'general:cae_percentage')['edit'];
        const view = new PercentInputWidget({
            value: this.model.get('cae_percentage'),
            title: 'Part de paiement direct par la CAE',
            field_name: 'cae_percentage',
            editable: editable,
        });
        this.showChildView('advance_percent', view);
    },
    onRender() {
        this.showDatePicker();
        this.showRemoteInvoiceNumber();
        if (this.config.request('has:form_section', 'general:supplier_id')) {
            this.showSupplierId();
        }
        if (this.config.request('has:form_section', 'general:supplier_orders')) {
            this.showSupplierOrders();
        }
        if (this.config.request('has:form_section', 'general:payer_id')) {
            this.showPayerId();
        }
        if (this.config.request('has:form_section', 'general:cae_percentage')) {
            this.showCaePercentage();
        }
    },
    onSuccessSync() {
        let facade = Radio.channel('facade');
        facade.trigger('navigate', 'index');
        this.render();
    },

});
export default SupplierInvoiceFormView;